﻿using System;
using System.IO;
using System.Net;

namespace Net.Formats.oEmbed
{
    /// <summary>
    /// Wrapper class mainly used for 
    /// easy substitution during unit testing
    /// </summary>
    public class ResourceLoader : IResourceLoader
    {
        /// <summary>
        /// This is used for oEmbed resource url discovery
        /// </summary>
        /// <param name="contentUrl">Original url for which oEmbed resource is required</param>
        /// <returns>Html content for the original url (hopefully containing discoverable
        /// link elements with oEmbed resource urls)</returns>
        public string GetResourceContent( Uri contentUrl )
        {
            var content = string.Empty;

            var webRequest = WebRequest.Create( contentUrl );
            var webResponse = webRequest.GetResponse( ) as HttpWebResponse;

            using ( var stream = new StreamReader( webResponse.GetResponseStream( ) ) )
            {
                content = stream.ReadToEnd( );
            }
            return content;
        }

        /// <summary>
        /// This is used to fetch the actual oEmbed response content
        /// for serialization to a response type
        /// </summary>
        /// <param name="resourceUrl">oEmbed resource url</param>
        /// <param name="format">Format of the oEmbed resource (XML or JSON)</param>
        /// <returns>oEmbed response content in the specified format</returns>
        public string GetResourceType( Uri resourceUrl, out ResponseFormat format )
        {
            string content = string.Empty;

            var webRequest = WebRequest.Create( resourceUrl );
            var webResponse = webRequest.GetResponse( ) as HttpWebResponse;            

            if ( webResponse.ContentType.Contains( "text/xml") 
                || webResponse.ContentType.Contains("application/xml") )
                format = ResponseFormat.XML;

            else if ( webResponse.ContentType.Contains( "application/json") )
                format = ResponseFormat.JSON;
            else
                throw new ArgumentException( "Format is not valid" );

            using ( var stream = new StreamReader( webResponse.GetResponseStream( ) ) )
            {
                content = stream.ReadToEnd( );
            }
            return content;
        }
    }
}